<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Auth extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->model('users_model');
        $this->load->helper('url');
    }

    public function index() {
        $this->load->library('session');
        $context['_message'] = $this->session->flashdata('_message');
        $this->load->view('login', $context);
    }

    public function login() {
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            p($_POST);
        }
    }

    public function register() {
        $this->load->library('form_validation');
        $this->load->view('register');
    }

    public function valid_username($username = null) {
        if ($_SERVER['REQUEST_METHOD'] != 'POST') {
            redirect(site_url('auth'));
        }
        if($username==null){
            $username=  $_POST['username'];
        }
        $notexist = FALSE;
        $success = FALSE;
        $errmsg = '';
        // 验证用户名格式
        if (preg_match('/^[a-z]\w{5,19}$/i', $username)) {
            $success = TRUE;
        } else {
            $errmsg = '用户名格式输入错误';
        }

        //验证用户名是否存在
        if ($success) {
            $success = $this->users_model->checkUserNotExist($username);
            if (!$success) {
                $errmsg = '用户已经存在';
            }
        }
        if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
            exit(json_encode(array('success' => $success, 'errmsg' => $errmsg)));
        }
        if ($errmsg) {
            $this->form_validation->set_message('valid_username', $errmsg);
        }
        return $success;
    }

//    private function valid_username($username){
//        
//    }
    public function register_user() {
        if ($_SERVER['REQUEST_METHOD'] != 'POST') {
            return;
        }
        $this->load->library('form_validation');
        $this->form_validation->set_rules('username', '用户名', 'callback_valid_username');
        $this->form_validation->set_rules('passwd', '密码', 'required');
        $this->form_validation->set_rules('hobby', '爱好', 'required');
        if ($this->form_validation->run()) {
            $userinfo = array(
                'user_name' => $this->input->post('username'),
                'passwd' => md5($this->input->post('passwd')),
            );
            $uid = $this->users_model->addUser($userinfo);
            if ($uid) {
                $this->load->library('session');
                $this->session->set_flashdata('_message', '注册成功');
                redirect('auth');
            }
        }
        $this->load->view('register');
    }

}

/* End of file login.php */
/* Location: ./application/controllers/login.php */